<template>
  <div class="income-container">
    <!-- 顶部统计卡片 -->
   <el-row :gutter="20" class="summary-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card">
          <div class="card-content">
            <div class="card-header-wrapper">
              <div class="card-icon monthly-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="card-title">当月收入</div>
            </div>
            <div class="card-value">¥{{ monthlyIncome.totalIncome.toFixed(2) }}</div>
            <div class="card-change" :class="monthlyIncome.growth >= 0 ? 'positive' : 'negative'">
              <el-icon v-if="monthlyIncome.growth >= 0"><CaretTop /></el-icon>
              <el-icon v-else><CaretBottom /></el-icon>
              {{ Math.abs(monthlyIncome.growth) }}% 较上月
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card">
          <div class="card-content">
            <div class="card-header-wrapper">
              <div class="card-icon total-icon">
                <el-icon><Wallet /></el-icon>
              </div>
              <div class="card-title">总收入</div>
            </div>
            <div class="card-value">¥{{ incomeSummary.totalPaid.toFixed(2) }}</div>
            <div class="card-stat">{{ incomeSummary.paidCount }} 笔收款</div>
          </div>
        </el-card> </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card">
          <div class="card-content">
            <div class="card-header-wrapper">
              <div class="card-icon unpaid-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="card-title">待收款</div>
            </div>
            <div class="card-value">¥{{ incomeSummary.totalUnpaid.toFixed(2) }}</div>
            <div class="card-stat">{{ incomeSummary.unpaidCount }} 笔待收</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card">
          <div class="card-content">
            <div class="card-header-wrapper">
              <div class="card-icon overdue-icon">
                <el-icon><AlarmClock /></el-icon>
              </div>
              <div class="card-title">逾期收款</div>
            </div>
            <div class="card-value">¥{{ incomeSummary.totalOverdue.toFixed(2) }}</div>
            <div class="card-stat">{{ incomeSummary.overdueCount }} 笔逾期</div>
          </div>
        </el-card> </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>年度收入趋势</span>
              <el-select v-model="selectedYear" placeholder="选择年份" @change="handleYearChange">
                <el-option
                  v-for="year in yearOptions"
                  :key="year"
                  :label="year + '年'"
                  :value="year"
                />
              </el-select>
            </div>
          </template>
          <div ref="yearlyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>最近收入记录</span>
              <el-button link type="primary" @click="viewAllIncomeDetails">查看全部</el-button>
            </div>
          </template>
          <div class="recent-list">
            <el-skeleton :rows="5" animated v-if="recentLoading" />
            <div v-else>
              <div v-for="(item, index) in recentIncome" :key="index" class="recent-item">
                <div class="recent-item-icon" :class="getBillStatusClass(item.status)">
                  <el-icon v-if="item.status === 'PAID'"><Check /></el-icon>
                  <el-icon v-else-if="item.status === 'UNPAID'"><Timer /></el-icon>
                  <el-icon v-else><Warning /></el-icon>
                </div>
                <div class="recent-item-content">
                  <div class="recent-item-title">{{ item.advertisementName || '广告费用' }}</div>
                  <div class="recent-item-date">{{ formatDateTime(item.status === 'PAID' ? item.paymentDate : item.createdTime) }}</div>
                </div>
                <div class="recent-item-amount" :class="{'amount-paid': item.status === 'PAID'}">
                  {{ item.status === 'PAID' ? '+' : '' }}¥{{ item.amount.toFixed(2) }}
                </div>
              </div>
              <el-empty v-if="recentIncome.length === 0" description="暂无收入记录" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入明细表格 -->
    <el-card shadow="hover" class="detail-card">
      <template #header>
        <div class="card-header">
          <span>收入明细</span>
          <div class="header-actions">
            <el-select v-model="filterStatus" placeholder="账单状态" clearable @change="handleStatusChange" style="width: 180px">
              <el-option label="全部" value="ALL" />
              <el-option label="已支付" value="PAID" />
              <el-option label="未支付" value="UNPAID" />
              <el-option label="已逾期" value="OVERDUE" />
            </el-select>
            <el-button type="primary" @click="exportIncomeDetails">
              <el-icon><Download /></el-icon> 导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="incomeDetails"
        style="width: 100%"
        border
        v-loading="detailsLoading"
        @row-click="handleBillClick"
      >
        <el-table-column prop="id" label="账单ID" width="100" />
        <el-table-column prop="advertisementName" label="广告名称" min-width="180">
          <template #default="scope">
            {{ scope.row.advertisementName || '未知广告' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getBillStatusType(scope.row.status)">
              {{ getBillStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="支付期限" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.dueDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentDate" label="支付时间" width="160">
          <template #default="scope">
            {{ scope.row.paymentDate ? formatDateTime(scope.row.paymentDate) : '未支付' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click.stop="viewBillDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 账单详情对话框 -->
    <el-dialog
      v-model="billDetailVisible"
      title="账单详情"
      width="600px"
      destroy-on-close
    >
      <div v-loading="billDetailLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="账单ID" :span="2">{{ currentBill.id }}</el-descriptions-item>
          <el-descriptions-item label="广告名称" :span="2">{{ currentBill.advertisementName || '未知广告' }}</el-descriptions-item>
          <el-descriptions-item label="广告主">{{ currentBill.advertiserName || '未知广告主' }}</el-descriptions-item>
          <el-descriptions-item label="账单金额">
            <span class="amount">¥{{ (currentBill.amount || 0).toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="账单状态">
            <el-tag :type="getBillStatusType(currentBill.status)">
              {{ getBillStatusText(currentBill.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付期限">{{ formatDateTime(currentBill.dueDate) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间" :span="2">
            {{ currentBill.paymentDate ? formatDateTime(currentBill.paymentDate) : '未支付' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentBill.createdTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentBill.updatedTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Money, Wallet, Timer, AlarmClock, Check, 
  Warning, Download, CaretTop, CaretBottom 
} from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import { getBills, getBillDetail } from '@/api/bill';
import { 
  getMonthlyIncome, 
  getYearlyIncomeStats, 
  getIncomeDetails, 
  getIncomeSummary, 
  getRecentIncomeRecords,
  exportIncomeData
} from '@/api/income';

// 状态变量
const yearlyChartRef = ref(null);
let yearlyChart = null;

const monthlyIncome = reactive({
  totalIncome: 0,
  growth: 0
});

const incomeSummary = reactive({
  totalPaid: 0,
  totalUnpaid: 0,
  totalOverdue: 0,
  paidCount: 0,
  unpaidCount: 0,
  overdueCount: 0
});

const recentIncome = ref([]);
const recentLoading = ref(false);

const incomeDetails = ref([]);
const detailsLoading = ref(false);
const filterStatus = ref('ALL');

const billDetailVisible = ref(false);
const billDetailLoading = ref(false);
const currentBill = reactive({});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 年度选择
const currentYear = new Date().getFullYear();
const yearOptions = [currentYear, currentYear - 1, currentYear - 2, currentYear - 3, currentYear - 4];
const selectedYear = ref(currentYear);
const yearlyStats = reactive({
  year: currentYear,
  yearlyTotal: 0,
  monthlyData: []
});

// 初始化数据
onMounted(() => {
  fetchMonthlyIncome();
  fetchIncomeSummary();
  fetchYearlyIncomeStats();
  fetchRecentIncome();
  fetchIncomeDetails();
  
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  if (yearlyChart) {
    yearlyChart.dispose();
    yearlyChart = null;
  }
});

// 获取月度收入
const fetchMonthlyIncome = async () => {
  try {
    const res = await getMonthlyIncome();
    if (res.data.code === 200) {
      monthlyIncome.totalIncome = res.data.data.totalIncome || 0;
      monthlyIncome.growth = res.data.growth || 0;
    } else {
      ElMessage.error(res.message || '获取月度收入失败');
    }
  } catch (error) {
    console.error('获取月度收入异常:', error);
    ElMessage.error('获取月度收入失败');
  }
};

// 获取收入汇总
const fetchIncomeSummary = async () => {
  try {
    const res = await getIncomeSummary();
    if (res.data.code === 200) {
      Object.assign(incomeSummary, res.data.data);
    } else {
      ElMessage.error(res.message || '获取收入汇总失败');
    }
  } catch (error) {
    console.error('获取收入汇总异常:', error);
    ElMessage.error('获取收入汇总失败');
  }
};

// 获取年度收入统计
const fetchYearlyIncomeStats = async () => {
  try {
    const res = await getYearlyIncomeStats(selectedYear.value);
    if (res.data.code === 200) {
      yearlyStats.year = res.data.data.year;
      yearlyStats.yearlyTotal = res.data.data.yearlyTotal;
      yearlyStats.monthlyData = res.data.data.monthlyData;
      renderYearlyChart();
    } else {
      ElMessage.error(res.message || '获取年度收入统计失败');
    }
  } catch (error) {
    console.error('获取年度收入统计异常:', error);
    ElMessage.error('获取年度收入统计失败');
  }
};

// 渲染年度图表
const renderYearlyChart = () => {
  if (!yearlyChartRef.value) return;
  
  if (!yearlyChart) {
    yearlyChart = echarts.init(yearlyChartRef.value);
  }
  
  const months = yearlyStats.monthlyData.map(item => item.month + '月');
  const values = yearlyStats.monthlyData.map(item => item.total);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>收入: ¥{c}'
    },
    title: {
      text: `${yearlyStats.year}年度总收入: ¥${yearlyStats.yearlyTotal.toFixed(2)}`,
      subtext: '',
      left: 'center',
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '60px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '月收入',
        type: 'line',
        data: values,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      }
    ]
  };
  
  yearlyChart.setOption(option);
};

// 获取最近收入记录
const fetchRecentIncome = async () => {
  recentLoading.value = true;
  try {
    const res = await getRecentIncomeRecords(5);
    console.info("最近收入记录",res)
    if (res.data.code === 200) {
      recentIncome.value = res.data.data || [];
    } else {
      ElMessage.error(res.message || '获取最近收入记录失败');
    }
  } catch (error) {
    console.error('获取最近收入记录异常:', error);
    ElMessage.error('获取最近收入记录失败');
  } finally {
    recentLoading.value = false;
  }
};

// 获取收入明细
const fetchIncomeDetails = async () => {
  detailsLoading.value = true;
  try {
    const params = {
      status: filterStatus.value,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    };
    
    const res = await getIncomeDetails(params.status, params.pageNum, params.pageSize);
    console.info("收入明细响应:", res);
    if (res.data.code === 200) {
      incomeDetails.value = res.data.data.records || [];
      pagination.total = res.data.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取收入明细失败');
    }
  } catch (error) {
    console.error('获取收入明细异常:', error);
    ElMessage.error('获取收入明细失败');
  } finally {
    detailsLoading.value = false;
  }
};

// 导出收入明细
const exportIncomeDetails = async () => {
  try {
    await exportIncomeData();
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出收入明细异常:', error);
    ElMessage.error('导出收入明细失败');
  }
};

// 查看账单详情
const viewBillDetail = async (bill) => {
  billDetailVisible.value = true;
  billDetailLoading.value = true;
  
  try {
    // 先显示列表中的数据
    Object.assign(currentBill, bill);
    
    // 然后获取详细信息
    const res = await getBillDetail(bill.id);
    console.log('查看账单详情:', res);
    if (res.data.code === 200) {
      Object.assign(currentBill, res.data.data);
    } else {
      ElMessage.error(res.message || '获取账单详情失败');
    }
  } catch (error) {
    console.error('获取账单详情异常:', error);
    ElMessage.error('获取账单详情失败');
  } finally {
    billDetailLoading.value = false;
  }
};

// 处理账单点击
const handleBillClick = (row) => {
  viewBillDetail(row);
};

// 查看所有收入明细
const viewAllIncomeDetails = () => {
  // 跳转到明细部分
  document.querySelector('.detail-card').scrollIntoView({ behavior: 'smooth' });
};

// 处理年份变更
const handleYearChange = () => {
  fetchYearlyIncomeStats();
};

// 处理状态筛选变更
const handleStatusChange = () => {
  pagination.current = 1;
  fetchIncomeDetails();
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchIncomeDetails();
};

// 处理分页页码变更
const handleCurrentChange = (page) => {
  pagination.current = page;
  fetchIncomeDetails();
};

// 处理窗口大小变化
const handleResize = () => {
  if (yearlyChart) {
    yearlyChart.resize();
  }
};

// 获取账单状态类型
const getBillStatusType = (status) => {
  switch (status) {
    case 'PAID': return 'success';
    case 'UNPAID': return 'warning';
    case 'OVERDUE': return 'danger';
    default: return 'info';
  }
};

// 获取账单状态文本
const getBillStatusText = (status) => {
  switch (status) {
    case 'PAID': return '已支付';
    case 'UNPAID': return '未支付';
    case 'OVERDUE': return '已逾期';
    default: return '未知';
  }
};

// 获取账单状态样式类
const getBillStatusClass = (status) => {
  switch (status) {
    case 'PAID': return 'status-paid';
    case 'UNPAID': return 'status-unpaid';
    case 'OVERDUE': return 'status-overdue';
    default: return '';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleString();
};
</script>

<style scoped>
.income-container {
  padding: 20px;
}

.summary-row,
.chart-row {
  margin-bottom: 20px;
}

.summary-card {
  height: 170px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 16px;
}

.card-icon .el-icon {
  font-size: 32px;
  color: white;
}

.monthly-icon {
  background-color: #409EFF;
}

.total-icon {
  background-color: #67C23A;
}

.unpaid-icon {
  background-color: #E6A23C;
}

.overdue-icon {
  background-color: #F56C6C;
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.card-change {
  font-size: 13px;
  display: flex;
  align-items: center;
}

.positive {
  color: #67C23A;
}

.negative {
  color: #F56C6C;
}

.card-stat {
  font-size: 13px;
  color: #606266;
}

.chart-card {
  height: 440px;
  margin-bottom: 20px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.detail-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.recent-list {
  height: 320px;
  overflow-y: auto;
}

.recent-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #EBEEF5;
}

.recent-item:last-child {
  border-bottom: none;
}

.recent-item-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
}

.recent-item-icon .el-icon {
  font-size: 20px;
  color: white;
}

.status-paid {
  background-color: #67C23A;
}

.status-unpaid {
  background-color: #E6A23C;
}

.status-overdue {
  background-color: #F56C6C;
}

.recent-item-content {
  flex: 1;
}

.recent-item-title {
  font-size: 14px;
  margin-bottom: 4px;
}

.recent-item-date {
  font-size: 12px;
  color: #909399;
}

.recent-item-amount {
  font-size: 16px;
  font-weight: bold;
}

.amount-paid {
  color: #67C23A;
}

.amount {
  font-weight: bold;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    width: 100%;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .chart-card {
    height: 300px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .recent-list {
    height: 250px;
  }
}
</style>